#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LEN 20
#define BUF 40
#define STARS "****************************************"
char* s_get(char* st, int n,FILE *fp);
int menu(void);
void command_mode(int , char*, char*);
void shell_mode();
void showfile(FILE *, FILE*);
int main(int argc, char * argv[]) 
{
	int mode;
	mode = menu();
	switch(mode){
		case 1:
			command_mode(argc, argv[1], argv[2]);
			break;
		case 2:
			shell_mode();
			break;
		default:
			break;
	}
	
	return 0;
}
int menu(void)
{
	int choice,status;
	puts(STARS);
	printf("         choose the input mode: \n");
	printf("1)command			2)shell\n");
	puts(STARS);
	while((status = scanf("%d", &choice) != 1) || choice<1 || choice >2)
	{
		if(status != 1)
			scanf("%*s");
		printf("please enter the right number: 1,2");			
	}
	return choice;		
}
 
void command_mode(int n, char* f1, char* f2)
{
	int flag = 0;
	FILE *fp1, *fp2;
	if(n !=3){
		fprintf(stderr, "something goes wrong\n");
		exit(EXIT_FAILURE);
	}
	if((fp1 = fopen(f1, "r")) == NULL){
		fprintf(stderr, "can't open the file\n");
		exit(EXIT_FAILURE);
	}
	if((fp2 = fopen(f2, "r")) == NULL){
		fprintf(stderr, "can't open the file\n");
		exit(EXIT_FAILURE);
	}	
	showfile(fp1, fp2);
	if(fclose(fp1) !=0 || fclose(fp2) !=0)
	{
		fprintf(stderr, "can not close the file:");
	}
	
}
void shell_mode()
{
	FILE *fp1, *fp2;
	char name1[LEN];
	char name2[LEN];
	printf("please enter the file name:\n");
	if(scanf("%s %s", name1, name2) == 2){
		if((fp1 = fopen(name1, "r")) == NULL){
			fprintf(stderr, "can't open the file\n");
			exit(EXIT_FAILURE);
		}
		if((fp2 = fopen(name2, "r")) == NULL){
			fprintf(stderr, "can't open the file\n");
			exit(EXIT_FAILURE);
		}				
	}
	showfile(fp1, fp2);
	if(fclose(fp1) !=0 || fclose(fp2) !=0)
	{
		fprintf(stderr, "can not close the file:");
	}
}
void showfile(FILE* fp1, FILE* fp2)
{
	char *status1;
	char word1[BUF];
	char word2[BUF];
	while((status1 = s_get(word1, 20, fp1))!= NULL && (s_get(word2, 20, fp2))!= NULL ){
			printf("%s\t", word1);
			printf("%s\t", word2);
			printf("\n");
//			scanf("%*s");
	}
	if(status1 != NULL)
	{
		printf("%s\t",word1);
		printf("\n");		
	}
	while(s_get(word1, 20, fp1)!= NULL)
	{
		printf("%s\t", word1);
		printf("\n");		
	}
	while(s_get(word2, 20, fp2)!= NULL)
	{
		printf("%s\t", word2);
		printf("\n");
	}


}
char* s_get(char* st, int n, FILE *fp)
{
	char* ret_val;
	int i = 0;
	ret_val = fgets(st, n, fp);
	if(ret_val)
	{
		while(st[i]!='\0' && st[i]!='\n')
			i++;
		if(st[i]=='\n')
			st[i] = '\0';
//		else	
//			while(getchar() != '\n')
//				continue;
	}
	return ret_val;
}
